package com.iqiyi.pps.epg.web.webapp.interceptor;

import com.iqiyi.kiwi.utils.JsonUtil;
import com.iqiyi.pps.epg.web.utils.WebApplicationContextUtil;
import com.iqiyi.pps.epg.core.model.base.BaseEntity;
import com.iqiyi.pps.epg.core.model.log.LogOperator;
import com.iqiyi.pps.epg.web.webapp.action.BaseAction;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.PreResultListener;
import org.apache.struts2.convention.annotation.Action;

import java.sql.Timestamp;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: Qiyi
 * Date: 12-5-31
 * Time: 下午4:18
 * 日志拦截器
 */
public class LogInterceptor extends AbstractInterceptor {

    private static final String[] methodString = new String[]{"list", "input", "select", "search"};

    @Override
    public String intercept(ActionInvocation actionInvocation) throws Exception {
        try {
            Object object = actionInvocation.getAction();
            if (object instanceof BaseAction) {
                if (isThrough(actionInvocation)) {
                    BaseAction baseAction = (BaseAction) object;
                    Object ob = baseAction.getModel();
                    if (ob != null && ob instanceof BaseEntity) {
                        BaseEntity baseEntity = (BaseEntity) ob;
                        if (baseEntity.getId() != null) {
                            //取操作实体 适用于变更操作
                            ob = WebApplicationContextUtil.getInstance().getFacadeManager().getLogOperatorManager().getObject(baseEntity.getClass(), baseEntity.getId())
                            ;
                        } else {
                            ob = null;
                        }
                    } else {
                        ob = null;
                    }
                    actionInvocation.addPreResultListener(new BeforeActionReturn(ob));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return actionInvocation.invoke();

    }

    private boolean isThrough(ActionInvocation actionInvocation) throws NoSuchMethodException {
        boolean flag = true;
        if ("execute".indexOf(actionInvocation.getProxy().getMethod()) != -1) {
            return false;
        }
        //如果注解 @Action(value="list") 含有以上字符串不会记录日志
        String methodAnnotation = actionInvocation.getAction().getClass().getMethod(actionInvocation.getProxy().getMethod()).getAnnotation(Action.class).value();
        for (String method : methodString) {
            if (methodAnnotation.indexOf(method) != -1) {
                flag = false;
                break;
            }
        }
        return flag;
    }


    private class BeforeActionReturn implements PreResultListener {
        private Object ob;

        public BeforeActionReturn(Object object) {
            this.ob = object;
        }

        @Override
        public void beforeResult(ActionInvocation actionInvocation, String s) {
            try {
                String actionName = actionInvocation.getAction().getClass().getName();//Action
                String packageName = actionInvocation.getAction().getClass().getPackage().getName();//packageName
                String methodName = actionInvocation.getProxy().getMethod();//method
                String type = getType(methodName);
                BaseAction newBaseAction = (BaseAction) actionInvocation.getAction();
                String ip = newBaseAction.getIp();//IP
                String operator = newBaseAction.getCurrentUser().getName();//操作者
                String object = null;
                Object o = newBaseAction.getModel();
                if (ob != null && o != null) {
                    object = JsonUtil.mergeObject(ob, o);
                }
                String info = newBaseAction.getLogInfo();
                saveOperatorLog(ip, operator, packageName.substring(packageName.lastIndexOf('.') + 1, packageName.length()), actionName, methodName, type, object, info);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        private void saveOperatorLog(String ip, String operator, String module, String action, String method, String type, String object, String info) {
            //保存日志信息
            LogOperator logOperator = new LogOperator();
            logOperator.setAction(action);
            logOperator.setCreateTime(new Timestamp(new Date().getTime()));
            logOperator.setUpdateTime(new Timestamp(new Date().getTime()));
            logOperator.setInfo(info);
            logOperator.setIp(ip);
            logOperator.setMethod(method);
            logOperator.setModule(module);
            logOperator.setObject(object);
            logOperator.setOperator(operator);
            logOperator.setType(type);
            WebApplicationContextUtil.getInstance().getFacadeManager().getLogOperatorManager().saveLogOperator(logOperator);
        }

        private String getType(String methodName) {
            //取操作类型
            char[] chars = methodName.toCharArray();
            int i = 0;
            for (char c : chars) {
                Pattern p = Pattern.compile("[A-Z]");
                Matcher m = p.matcher(Character.toString(c));
                if (m.matches()) {
                    break;
                }
                i++;

            }
            return methodName.substring(0, i);
        }


    }

}
